package com.bnlr.lrparking.appui.home;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.Address;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.appui.message.MyMessageActivity;
import com.bnlr.lrparking.appui.stall.ParKActivity;
import com.bnlr.lrparking.appui.stall.SelectDevelopersActivity;
import com.bnlr.lrparking.appui.stall.SelectStallSourceActivity;
import com.bnlr.lrparking.appui.stall.StallActivity;
import com.bnlr.lrparking.appui.stall.StallDealActivity;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.util.BDMapUtils;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.appui.carplace.CarPlaceDetailActivity;
import com.bnlr.lrparking.appui.chose.ChoseCityActivity;
import com.bnlr.lrparking.appui.web.BannerWebActivity;
import com.bnlr.lrparking.appui.carport.recommend.RecommendParkingActivity;
import com.bnlr.lrparking.appui.search.RentBuyStallActivity;
import com.bnlr.lrparking.appui.search.SeachActiity;
import com.bnlr.lrparking.appui.login.VerificaActivity;
import com.bnlr.lrparking.adapter.RecommendParkAdapter;
import com.bnlr.lrparking.adapter.StallHeaderGirdAdapter;
import com.bnlr.lrparking.base.BaseAutoScrollUpTextView;
import com.bnlr.lrparking.base.BaseFragment;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.constant.IntentConstant;
import com.bnlr.lrparking.model.AdvertisementObject;
import com.bnlr.lrparking.model.AppPhoneBean;
import com.bnlr.lrparking.model.BannerM;
import com.bnlr.lrparking.model.CarPlaceData;
import com.bnlr.lrparking.model.ExchangeRateBean;
import com.bnlr.lrparking.model.HomeNewM;
import com.bnlr.lrparking.model.HomePopBean;
import com.bnlr.lrparking.model.ParkNumBean;
import com.bnlr.lrparking.model.RecommendParkBean;
import com.bnlr.lrparking.constant.DataServer;
import com.bnlr.lrparking.model.Location;
import com.bnlr.lrparking.widget.NativeDialog;
import com.bnlr.lrparking.reserve.ExampleUtil;
import com.bnlr.lrparking.constant.Params;
import com.bnlr.lrparking.appui.carport.CarportBuildActivity;
import com.bnlr.lrparking.appui.carport.CarportShareActivity;
import com.bnlr.lrparking.appui.carport.recommend.ChooseCommunityActivity;
import com.bnlr.lrparking.util.GlideImageLoader;
import com.bnlr.lrparking.view.MainScrollUpAdvertisementView;
import com.bnlr.lrparking.widget.PresentShareDialog;
import com.bnlr.lrparking.widget.refresh.RefreshHolderUtil;
import com.bnlr.lrparking.widget.refresh.XRefreshLayout;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.bnlr.nohttp.CustomJavaHttpListener;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.jpush.android.api.JPushInterface;

/**
 * @author hp
 * @date 2017/8/14
 * 车位交易
 */

public class StallDealFragment extends BaseFragment {

    private Unbinder unbinder;
    @BindView(R.id.rv_stall)
    RecyclerView rvStall;
    @BindView(R.id.swipe_stall)
    XRefreshLayout swipeRefreshLayout;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.et_title_search)
    TextView tvHint;
    @BindView(R.id.see_more)
    RelativeLayout seeMore;
    @BindView(R.id.tv_is_debug)
    TextView tv_is_debug;
    @BindView(R.id.tv_location_result)
    TextView tvLocationResult;
    @BindView(R.id.main_advertisement_view)
    MainScrollUpAdvertisementView mMainScrollUpAdvertisementView;
    private Intent intent;
    /**
     * 轮播
     */
    private Banner bannerLin;
    /**
     * 图片 banner list  1
     */
    private List<String> topBannerList = new ArrayList<>();
    /**
     * 图片 banner list  2
     */
    private List<BannerM.DataBean> bannerTop = new ArrayList<>();
    /**
     * 推荐停车场list
     */
    private List<RecommendParkBean.DataBean> RecommendParkList=new ArrayList<>();
    private RecommendParkBean recommendParkBean;
    private RecommendParkAdapter recommendParkAdapter;
    private int currentPage = 1;
    private LocationClient mLocationClient = null;
    private BaiduMap mBaiDuMap = null;
    private BDMapUtils mapUtils = null;
    private LocationListener mLocationListener = null;
    private TextureMapView mapView = null;
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";
    public static boolean isForeground = false;
    private int waitReadMessage;
    @BindView(R.id.image_red_dot)
    ImageView image_red_dot;
    private String successLocation = "";
    private TextView carPlaceCount;
    private View mView;
    private ArrayList<AdvertisementObject> mDataList = new ArrayList<AdvertisementObject>();  // 文字轮播广告list
    private int requestCount = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_stalldeal1, container, false);
        unbinder = ButterKnife.bind(this, mView);
        if (Urls.isDebug) {
            tv_is_debug.setVisibility(View.VISIBLE);
        }
        initView();
        return mView;
    }

    @OnClick({R.id.lay_search, R.id.rely_message, R.id.rely_dw, R.id.ll_go_parking, R.id.see_more
    ,R.id.tv_location_result})
    public void stallOnClick(View view) {
        switch (view.getId()) {
            case R.id.lay_search:    // 搜索
                startActivity(new Intent(getActivity(), SeachActiity.class)
                        .putExtra(IntentConstant.IS_ALL_SEARCH, true));
               /* Intent intent = new Intent(getActivity(), SeachActiity.class);
                intent.putExtra("dealType", "10");
                intent.putExtra("developers", "0");
                AppConfig.getInstance().putString("spaceOwnerType", "2");
                startActivity(intent);*/
                break;
            case R.id.rely_message:  // 我的消息
                if (AppConfig.getInstance().getBoolean("isLogin", false)) {
                    startActivity(new Intent(getActivity(), MyMessageActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), VerificaActivity.class));
                }
                break;
            case R.id.rely_dw:
                startActivityForResult(new Intent(getActivity(), ChoseCityActivity.class)
                        .putExtra("city_name", successLocation), 1111);
                break;

            case R.id.see_more:
                Intent intent1 = new Intent(getActivity(), SelectDevelopersActivity.class);
                intent1.putExtra("dealType", "11");
                intent1.putExtra("spaceowertype", "1");
                startActivity(intent1);
                break;
            case R.id.ll_go_parking:
                startActivity(ParKActivity.class);
                break;
            case R.id.tv_location_result:
                requestLocationPermission();
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1111 && resultCode == 2222) {
            String selectCity = data.getStringExtra("picked_city");
            tvCity.setText(selectCity);
            AppConfig.getInstance().putString("strCity", selectCity);
            currentPage = 1;
        }
    }

    private void initView() {
        GetHomePageNews();
        getFeedbackPhone();
        presentShareValue();
        getExchangeRate();
        tvHint.setText("请输入类别或关键字");
        registerMessageReceiver();
        JPushInterface.init(getActivity().getApplicationContext());
        rvStall.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvStall.setNestedScrollingEnabled(false);
        initBannerHeader(mView);
        initHeadGirdView(mView);
        initMapHeader(mView);
        swipeRefreshLayout.setRefreshViewHolder(RefreshHolderUtil.getRefreshHolder(getActivity()));
        swipeRefreshLayout.setDelegate(new XRefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public void onBGARefreshLayoutBeginRefreshing(XRefreshLayout refreshLayout) {
                currentPage = 1;
                getBanner();
                GetHomePageNews();
                getFeedbackPhone();
                getExchangeRate();
                getRecommendPark();
            }

            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(XRefreshLayout refreshLayout) {
                return false;
            }

        });
        recommendParkAdapter= new RecommendParkAdapter(RecommendParkList);
        rvStall.setAdapter(recommendParkAdapter);
        rvStall.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(getActivity(), CarPlaceDetailActivity.class);
                CarPlaceData carPlaceData = new CarPlaceData();
                RecommendParkBean.DataBean rpdb = RecommendParkList.get(position);
                carPlaceData.setId(rpdb.getID());
                carPlaceData.setAddress(rpdb.getAddress());
                carPlaceData.setChewei(rpdb.getChewei());
                carPlaceData.setIsFavorite(rpdb.getIsFavorite());
                carPlaceData.setIsjoin(rpdb.getIsjoin());
                carPlaceData.setJuli(rpdb.getJuli());
                carPlaceData.setLat(rpdb.getLat());
                carPlaceData.setLng(rpdb.getLng());
                carPlaceData.setMaxsellingprice(rpdb.getMaxsellingprice());
                carPlaceData.setMinsellingprice(rpdb.getMinsellingprice());
                carPlaceData.setName(rpdb.getName());
                carPlaceData.setOpentime(rpdb.getOpentime());
                carPlaceData.setPhone(rpdb.getPhone());
                carPlaceData.setSellingcount(rpdb.getSellingcount());
                carPlaceData.setSharevalue(rpdb.getSharevalue());
                intent.putExtra("CarPlace", carPlaceData);
                startActivity(intent);
            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemChildClick(adapter, view, position);
                Location loc_now = new Location(Params.CurrentLat, Params.CurrentLon, "起始点");
                Location loc_end = new Location(Double.valueOf(RecommendParkList.get(position).getLat()), Double.valueOf(RecommendParkList.get(position).getLng()), "终点");
                NativeDialog msgDialog = new NativeDialog(getActivity(), loc_now, loc_end);
                msgDialog.show();
            }
        });
    }

    /**
     * 获取推荐停车场列表
     */
    private void getRecommendPark() {
        Log.i("TAG", "getRecommendPark");
        try {
            Request mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "GetRecommendPark");
            mRequest.add("lng", Params.CurrentLon);
            mRequest.add("lat", Params.CurrentLat);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));

            Log.i("TAG", "getRecommendPark  mRequest"+ mRequest);

            // 添加到请求队列+
            CallServer.getRequestInstance().add(getActivity(), mRequest,
                    new CustomHttpListener<RecommendParkBean>(getActivity(), true, RecommendParkBean.class) {
                        @Override
                        public void doWork(RecommendParkBean data, String code) {
                            if ("1".equals(code)) {
                                Log.i("TAG", "getRecommendPark  mRequest"+ data.toString());
                                RecommendParkList.clear();
                                if (data.getData() != null && data.getData().size() > 0) {
                                    RecommendParkList.addAll(data.getData());
                                }
                                Log.i("TAG", "getRecommendPark  mRequest"+ RecommendParkList.toString());
                                recommendParkAdapter.notifyDataSetChanged();

                            }
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {

                        }
                    }, false);
        } catch (Exception e) {
        }
    }

    /**
     * 获取比率
     */
    private void getExchangeRate() {
        Log.i("TAG", "getExchangeRate");
        try {
            requestCount++;
            mRequest = NoHttp.createStringRequest(Urls.BASE_JAVA_URL+"system/getExchangeScale", LrConstant.POST);
            CallServer.getRequestInstance().add(getActivity(), mRequest,
                    new CustomJavaHttpListener<ExchangeRateBean>(getActivity(), true, ExchangeRateBean.class) {
                        @Override
                        public void doWork(ExchangeRateBean data, int code) {
                            if (data.getModel() != null && !TextUtils.isEmpty(data.getModel())) {
                                LrConstant.RATE_VALUE = Integer.valueOf(data.getModel());
                            }

                        }

                        @Override
                        public void onFinally(String obj, int code, boolean isSucceed) throws JSONException {
                            super.onFinally(obj, code, isSucceed);
                            if (code !=0 && requestCount < 3) {
                                getExchangeRate();
                            }
                        }
                    }, false);
        } catch (Exception e) {
        }
    }

    /**
     * 请求弹窗
     */
    private void presentShareValue() {
        Log.i("TAG", "presentShareValue");
        String splish = AppConfig.getInstance().getString("splish", "");
        if (splish.equals("1")) {
            try {
                Request mRequest = NoHttp.createStringRequest(Urls.COMMON_IP, LrConstant.POST);
                mRequest.add("action", "GetPopMessage");
                // 添加到请求队列+
                CallServer.getRequestInstance().add(getActivity(), mRequest,
                        new CustomHttpListener<HomePopBean>(getActivity(), true, HomePopBean.class) {
                            @Override
                            public void doWork(HomePopBean data, String code) {
                                if ("1".equals(code)) {
                                    AppConfig.getInstance().putString("splish", "2");
                                    PresentShareDialog.newInstance(data.getData())
                                            .showDialog(getActivity().getSupportFragmentManager());
                                }
                            }

                            @Override
                            public void onFinally(JSONObject obj, String code, boolean isSucceed) {

                            }
                        }, false);
            } catch (Exception e) {
            }

        }

    }

    /**
     * 获取反馈电话
     */
    private void getFeedbackPhone() {
        Log.i("TAG", "getFeedbackPhone");
        try {
            Request mRequest = NoHttp.createStringRequest(Urls.COMMON_IP, LrConstant.POST);
            mRequest.add("action", "GetAppPhone");

            // 添加到请求队列+
            CallServer.getRequestInstance().add(getActivity(), mRequest,
                    new CustomHttpListener<AppPhoneBean>(getActivity(), true, AppPhoneBean.class) {
                        @Override
                        public void doWork(AppPhoneBean data, String code) {
                            if ("1".equals(code)) {
                                AppConfig.getInstance().putString("app_phone", data.getData());
                            }
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            if (!"1".equals(code)) {
                                AppConfig.getInstance().putString("app_phone", "4008097095");
                            }
                        }
                    }, false);

        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }
    }

    /**
     * 获取首页的滚动新闻
     */
    private void GetHomePageNews() {
        Log.i("TAG", "GetHomePageNews");
        try {
            Request mRequest = NoHttp.createStringRequest(Urls.COMMON_IP, LrConstant.POST);
            mRequest.add("action", "GetHomePageNews");

            // 添加到请求队列+
            CallServer.getRequestInstance().add(getActivity(), mRequest,
                    new CustomHttpListener<HomeNewM>(getActivity(), true, HomeNewM.class) {
                        @Override
                        public void doWork(HomeNewM data, String code) {
                            if ("1".equals(code)) {
                                mDataList.clear();
                                mMainScrollUpAdvertisementView.stop();
                                for (int i = 0; i < data.getData().size(); i++) {
                                    AdvertisementObject advertisementObject = new AdvertisementObject();
                                    if (data.getData().get(i).getType() == 0) {
                                        advertisementObject.title = "";
                                    } else if (data.getData().get(i).getType() == 1) {
                                        advertisementObject.title = "公告";
                                    } else if (data.getData().get(i).getType() == 2) {
                                        advertisementObject.title = "新闻";
                                    }
                                    advertisementObject.info = data.getData().get(i).getMessageInfo();
                                    mDataList.add(advertisementObject);
                                }
                                mMainScrollUpAdvertisementView.setData(mDataList);
                                mMainScrollUpAdvertisementView.setTextSize(13);
                                mMainScrollUpAdvertisementView.setTimer(2500);
                                mMainScrollUpAdvertisementView.start();
                                mMainScrollUpAdvertisementView.setOnItemClickListener(new BaseAutoScrollUpTextView.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(int position) {
                                        // TODO 首页广告滚动条 点击处理
                                    }
                                });
                            }
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                        }
                    }, false);
        } catch (Exception e) {
        }
    }

    /**
     * 地图
     *
     * @param mView
     */
    private void initMapHeader(View mView) {
        mapView = (TextureMapView) mView.findViewById(R.id.map);
        carPlaceCount = (TextView) mView.findViewById(R.id.car_place_count);
        mapUtils = new BDMapUtils();
        mapUtils.configMap(mapView);
        mBaiDuMap = mapView.getMap();
        //禁止平移
        mBaiDuMap.getUiSettings().setScrollGesturesEnabled(false);
        mBaiDuMap.getUiSettings().setZoomGesturesEnabled(false);
        mBaiDuMap.getUiSettings().setRotateGesturesEnabled(false);
        mapUtils.initBaiDuMap(mBaiDuMap);
        mLocationClient = new LocationClient(getActivity(), mapUtils.locationOption());
        mLocationListener = new LocationListener();
        mLocationClient.registerLocationListener(mLocationListener);
        requestLocationPermission();
        mBaiDuMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                startActivity(ParKActivity.class);
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });
    }

    /**
     * 定位回调
     */
    private class LocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            //  定位监听
            if (bdLocation == null) {
                AppConfig.getInstance().putString("strCity", "郑州市");
                return;
            }
            if (bdLocation.getCity() == null) {
                successLocation = "郑州市";
                AppConfig.getInstance().putString("strCity", "郑州市");
            } else {
                successLocation = bdLocation.getCity();
                AppConfig.getInstance().putString("strCity", bdLocation.getCity());
            }
            if (bdLocation.getAddress() != null) {
                Address address = bdLocation.getAddress();
                if (address.city!= null && address.district!= null && address.street!= null) {
                    tvLocationResult.setText(address.city+address.district+address.street);
                } else {
                    tvLocationResult.setText("重新定位");
                }
            } else {
                tvLocationResult.setText("重新定位");
            }
            Params.CurrentLat = bdLocation.getLatitude();
            Params.CurrentLon = bdLocation.getLongitude();
            tvCity.setText(bdLocation.getCity());
            mapUtils.moveMapStatus(mBaiDuMap);

            getParkData();
            getRecommendPark();
        }
    }


    /**
     * 获取定位周边车场
     */
    private void getParkData() {
        Log.i("TAG", "getParkData   start!");
        try {
            Request mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "GetParkByLocationNum");
            mRequest.add("m", "200");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("lng", Params.CurrentLon);
            mRequest.add("lat", Params.CurrentLat);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));

            // 添加到请求队列+
            CallServer.getRequestInstance().add(getActivity(), mRequest,
                    new CustomHttpListener<ParkNumBean>(getActivity(), true, ParkNumBean.class) {
                        @Override
                        public void doWork(ParkNumBean data, String code) {
                            Log.i("TAG", "getParkData   ParkNumBean !" + data.toString());
                            if ("1".equals(code)) {
                                carPlaceCount.setText(data.getData().getCount() + "");
                            }
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                        }
                    }, false);
        } catch (Exception e) {
        }
    }

    private void requestLocationPermission() {
        if ((ContextCompat.checkSelfPermission(getActivity(), "android.permission.ACCESS_COARSE_LOCATION")) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{"android.permission.ACCESS_COARSE_LOCATION"}, 66);
        } else {
            mLocationClient.start();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 66) {
            if (grantResults != null) {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mLocationClient.start();
                    mLocationClient.requestLocation();
                } else {
                    ToastUtils.showShort("用户已拒绝定位权限，请在设置中赋予权限");
                }
            }
        }
    }

    private void initHeadGirdView(View headerView) {
        RecyclerView girdView = (RecyclerView) headerView.findViewById(R.id.stall_header_grid);
        girdView.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        StallHeaderGirdAdapter adapter = new StallHeaderGirdAdapter(DataServer.getHeaderGirdData());
        girdView.setAdapter(adapter);
        girdView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                switch (position) {
                    case 0:
                        if (Params.IS_HAVE_CHOOSE_PARKING) {
                            intent = new Intent(getActivity(), RecommendParkingActivity.class);
                            intent.putExtra("recommend_tag",1);
                            startActivity(intent);
                        } else {
                            intent = new Intent(getActivity(), ChooseCommunityActivity.class);
                            startActivity(intent);
                        }
                        break;
                    case 1:
                        intent = new Intent(getActivity(), SelectStallSourceActivity.class);
                        intent.putExtra("dealType", "11");
                        startActivity(intent);
                        break;
                    case 2:
                        intent = new Intent(getActivity(), StallDealActivity.class);
                        intent.putExtra("dealType", "10");
                        intent.putExtra("spaceowertype", "0");
                        intent.putExtra("developId", "0");
                        startActivity(intent);
                        break;
                    case 3:
                        intent = new Intent(getActivity(), RentBuyStallActivity.class);
                        intent.putExtra("dealType", "21");
                        intent.putExtra("developers", "0");
                        startActivity(intent);
                        break;
                    case 4:
                        intent = new Intent(getActivity(), RentBuyStallActivity.class);
                        intent.putExtra("dealType", "20");
                        startActivity(intent);
                        break;
                    case 5:
                        intent = new Intent(getActivity(), StallActivity.class);
                        startActivity(intent);
                        break;
                    case 6:
                        if (!AppConfig.getInstance().getBoolean("isLogin",false)) {
                            startActivity(new Intent(getActivity(), VerificaActivity.class));
                            return;
                        } else {
                            startActivity(CarportShareActivity.class);
                        }
                        break;
                    case 7:
                        if (!AppConfig.getInstance().getBoolean("isLogin",false)) {
                            startActivity(new Intent(getActivity(), VerificaActivity.class));
                            return;
                        } else {
                            startActivity(CarportBuildActivity.class);
                        }
                        break;
                    default:
                        break;
                }
            }
        });
    }

    /**
     * 初始化 banner
     * 请求数据，添加点击监听
     *
     * @param mView
     */
    private void initBannerHeader(View mView) {
        bannerLin = (Banner) mView.findViewById(R.id.bannerLin);
        getBanner();
        bannerLin.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                intent = new Intent(getActivity(), BannerWebActivity.class);
                intent.putExtra("Url", bannerTop.get(position).getLinkUrl());
                startActivity(intent);
            }

        });
    }

    /**
     * 广告位请求方法
     */
    private void getBanner() {
        LogUtils.i("getBanner");
        try {
            mRequest = NoHttp.createStringRequest(Urls.COMMON_IP, LrConstant.POST);
            mRequest.add("action", "GetBannerList");
            mRequest.add("Location", "2");
            CallServer.getRequestInstance().add(getActivity(), mRequest,
                    new CustomHttpListener<BannerM>(getActivity(), true, BannerM.class) {
                        @Override
                        public void doWork(BannerM data, String code) {
                            if ("1".equals(code)) {
                                bannerTop.clear();
                                topBannerList.clear();
                                for (int i = 0; i < data.getData().size(); i++) {
                                    bannerTop.add(data.getData().get(i));
                                    topBannerList.add(data.getData().get(i).getImageUrl());
                                }
                                bannerLin.setImages(topBannerList)
                                        .setDelayTime(4000)
                                        .setImageLoader(new GlideImageLoader())
                                        .start();
                            }
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                swipeRefreshLayout.endRefreshing();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {

        }
    }
    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mMessageReceiver, filter);
    }

    public static class MessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                    String messge = intent.getStringExtra(KEY_MESSAGE);
                    String extras = intent.getStringExtra(KEY_EXTRAS);
                    StringBuilder showMsg = new StringBuilder();
                    showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                    if (!ExampleUtil.isEmpty(extras)) {
                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                    }
                }
            } catch (Exception e) {
            }
        }
    }

    /**
     * 设置用户信息
     */
    private void initPersonInfo() {
        //消息红点
        if (waitReadMessage > 0) {
            image_red_dot.setVisibility(View.VISIBLE);
        } else {
            image_red_dot.setVisibility(View.GONE);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onStop() {
        //取消注册传感器监听
        super.onStop();
        if (mapView != null) {
            mapView.onPause();

        }
        if (mLocationClient != null) {
            mLocationClient.stop();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
        /**
         * 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
         */
        isForeground = true;
        if (AppConfig.getInstance().getBoolean("isLogin", false)) {
//            getUserInfo();

        }
    }

    private void getUserInfo() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "GetUserInfoById");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            // 添加到请求队列
            CallServer.getRequestInstance().add(getActivity(), mRequest,
                    new CustomHttpListener<JSONObject>(getActivity(), false, null) {
                        @Override
                        public void doWork(JSONObject data, String code) {
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if ("1".equals(code)) {
                                    JSONObject object = obj.getJSONObject("data");
                                    waitReadMessage = object.getInt("waitReadMessage");
                                    initPersonInfo();
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, false);
        } catch (Exception e) {

        }
    }

    @Override
    public void onPause() {
        mapView.onPause();
        super.onPause();
        isForeground = false;
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //退出时销毁定位
        if (mLocationClient != null) {
            mLocationClient.stop();
        }
        //关闭定位图层
        mBaiDuMap.setMyLocationEnabled(false);
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        if (mapView != null) {
            mapView.onDestroy();
        }
        mapView = null;
    }
}
